$(document).ready(function () {
        	
        	var mappingfields=null;
        	$.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/rule/getValidationRules",
	    		'datatype': "json",
	    		'success': function(data){
	    			mappingfields = data;
	    			//console.log(mappingfields);
	    		}            
			});
        	
        	
        	var initialData = null;
        	$.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/mapping/fieldmappings",
	    		'datatype': "json",
	    		'success': function(data){
	    			initialData = data;
	    			//console.log(initialData);
	    		}            
			});

        	var ezopsfieldjson=null;
        	$.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/mapping/ezopsfieldslookup",
	    		'datatype': "json",
	    		'success': function(data){
	    			ezopsfieldjson = data;
	    		}            
			});
        	
        	var clientfieldjson=null;
        	$.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/mapping/clientfieldslookup",
	    		'datatype': "json",
	    		'success': function(data){
	    			clientfieldjson = data;
	    		}            
			});
        	
        	/**
        	 * Asset class lookup
        	 */
        	
        	
            var GridModel = function (rules) {
                this.rules = ko.observableArray(rules);

                this.addRulesRow = function () {
                	console.log('In add');
                    // add a new item.
                    //if (this.rules().length < 20) {
                	var newRule = {fieldName: "out1", ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookup: "Trade01", refColumn: "resource", mandatory: "Y"};
                	this.rules.push(newRule);
                	//$("#jqxgrid").jqxGrid('addrow', null, newRule, 'last');
                	//if (source) source.totalrecords = this.items().length;
               		$("#fieldmappinggrid").jqxGrid('updatebounddata');
                       // $("#fieldmappinggrid").jqxGrid('addrow', null, newRule, 'last');
                        //this.rules.push(newRule);
                        /*if(this.rules.length > 0){
                        	$("#fieldmappinggrid").jqxGrid('addrow', null, newRule, 'last');
                        }*/
                        
                    //}
                        //console.log(this.rules.length);
                };

                this.removeRulesRow = function () {
                	console.log('In remove');
                    // remove the last item.
                    this.rules.pop();
                };
                
                this.deleteRow = function () {
                	console.log('In delete selected row');
                	//console.log(rules.length);
                	var selectedrowindex = $("#fieldmappinggrid").jqxGrid('getselectedrowindex');
                    //console.log(selectedrowindex);
                    var rowscount = $("#fieldmappinggrid").jqxGrid('getdatainformation').rowscount;
                    //console.log(rowscount);
                   // if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
                        var id = $("#fieldmappinggrid").jqxGrid('getrowid', selectedrowindex);
                        $("#fieldmappinggrid").jqxGrid('deleterow', id);
                        //this.rules.splice(selectedrowindex,1);
                        this.rules.remove(this.rules()[id]);
                    //}
                	//console.log(ko.toJSON(rules));
                };
                
                this.saveOrUpdateRulesRow = function (){
                	console.log('In save or Update');
                	var jsonArr = [];
                	$.each(rules, function(i, item){
                		var jsonField = {};
                		jsonField["clientFieldId"] = item.clientFieldId;
                		jsonField["ezopsFieldId"] = item.ezopsFieldId;
                		jsonArr.push(jsonField);
                	});
                	var jsonStr = JSON.stringify(jsonArr);
                	//console.log(jsonStr);
                	$.ajax({
                		headers: { 
               		        'Accept': 'application/json',
               		        'Content-Type': 'application/json' 
               		    },
               		    'type': 'POST',
               		    'data': ko.toJSON(jsonArr),
        	    		url: ezopsContextPath+"/mapping/savefieldmappings",
        	    		'datatype': "json",
        	    		success: function(data, textStatus, jqXHR)
        	    	    {
        	    	        //data - response from server
        	    			showAlertSuccess('<strong>' + 'Mappings are succesfully saved.' + '</strong>');
        	    	    },
        	    	    error: function (jqXHR, textStatus, errorThrown)
        	    	    {
        	    	 
        	    	    }
        			}); 
                };
                
                this.selectionChanged = function() {
                	console.log('In selection');
                  this.rules.removeAll();
                  var newData=  $.ajax({
			    		'async': false,
			    		'global': false,
			    		'url': ezopsContextPath+"/mapping/fieldmappings?assetclass="+2,
			    		'datatype': "json",
			    		'success': function(data,data1){
			    			
			                 return data;
			    		}            
					});
                  ko.utils.arrayPushAll(this.rules(), newData.responseJSON);
                  this.rules.valueHasMutated();

               };
            };
            
           // var gridModel = new GridModel(initialData);
           //ko.applyBindings(new GridModel(initialData));
            
             
        
           
            
     var mappinguimodel = function(datamodel){
               //console.log('datamodel '+datamodel); 
            var source = {
                    localdata: datamodel.rules,
                    datatype: 'observablearray',
                    datafields: [
                        { name: 'clientFieldId', type: 'string' },
                        { name: 'fieldName', type: 'string' },
                        { name: 'ezopsFieldId', type: 'string' },
                        { name: 'ezopsFieldName', type: 'string' },
                        { name: 'assetClass', type: 'string' },
                        { name: 'type', type: 'string' },
                        { name: 'range', type: 'string' },
                        { name: 'dbLookup', type: 'string' },                        
                        { name: 'refColumn', type: 'string' },
                        { name: 'mandatory', type: 'string' }],
                        deleterow: function (rowid, commit) {
                            commit(true);
                        },
                        addrow: function (rowid, rowdata, position, commit) {
                            // synchronize with the server - send insert command
                            // call commit with parameter true if the synchronization with the server is successful 
                            //and with parameter false if the synchronization failed.
                            commit(true);
                        }
                };
            
            var dataAdapter = new $.jqx.dataAdapter(source);
            
            $("#fieldmappinggrid").jqxGrid(
                    {
                    	source: dataAdapter, autoheight: true,                
                		editable: true,
                        width: '100%',
                        autorowheight: true,
                        autoheight: true,
                        pageable: true,
                    columns: [
                    { text: 'Client Field', align: 'center', dataField: 'clientFieldId', columntype: 'dropdownlist', displayfield: 'fieldName', width: '15%', pinned: true, initeditor: function (row, column, editor) {
                           // assign a new data source to the dropdownlist.
                           editor.jqxDropDownList({ displayMember: 'fieldName', valueMember: 'clientFieldId', source: clientfieldjson });
                       } },
                    { text: 'EZOPS Field', align: 'center', dataField: 'ezopsFieldId', columntype: 'dropdownlist', displayfield: 'ezopsFieldName', width: '15%', pinned: true, initeditor: function (row, column, editor) {
                           // assign a new data source to the dropdownlist.
                           editor.jqxDropDownList({ displayMember: 'ezopsFieldName', valueMember: 'ezopsFieldId', source: ezopsfieldjson });
                          editor.bind('change', function (event) {
                        	  //var datarow = $("#fieldmappinggrid").jqxGrid('getrowdata', row);
                        	  var ezopsFieldNm = event.args.item.originalItem.ezopsFieldName;
                        	   setCellvalues(ezopsFieldNm,row); 
                           });
                       } 
                    },
                    { text: 'Asset Types', align: 'center', dataField: 'assetClass', width: '12%', editable: false, pinned: true },
                    { text: 'Type', align: 'center', dataField: 'type', width: '10%', editable: false, pinned: true },
                    { text: 'Range', dataField: 'range', align: 'center', width: '10%', editable: false, pinned: true  },
                    { text: 'DB Lookup', dataField: 'dbLookup', width: '14%', editable: false, align: 'center' , pinned: true },
                    { text: 'Ref Column', align: 'center', dataField: 'refColumn', editable: false, width: '15%', pinned: true },
                    { text: 'Mandatory', align: 'center', dataField: 'mandatory', width: '9%', editable: false, pinned: true  },
                    ]
                    });
            /*$('#addButton').jqxButton({});
            $('#removeButton').jqxButton({});
            $('#saveButton').jqxButton({});*/

            function setCellvalues(ezopsFieldNm,row){
            	$.each(mappingfields, function(i, item) {
            	    if(item.ezopsFieldName.toUpperCase() == ezopsFieldNm.toUpperCase()){
            		//console.log(row);
            	    	 $('#fieldmappinggrid').jqxGrid('setcellvalue', row, "type", item.type);
                         $('#fieldmappinggrid').jqxGrid('setcellvalue', row, "range", item.range);
                         $('#fieldmappinggrid').jqxGrid('setcellvalue', row, "dbLookup", item.dbLookupName);
                         $('#fieldmappinggrid').jqxGrid('setcellvalue', row, "refColumn", item.refColumnName);
                         $('#fieldmappinggrid').jqxGrid('setcellvalue', row, "mandatory", item.mandatoryName);
                         
            	   }
            	});
           }
            
           ko.applyBindings(datamodel,document.getElementById('fieldmappinggridparent'));
     };
     			
     /**
      * Populate Ezops Client Field
      */
     $.ajax({
			type : "GET",
			'url' : ezopsContextPath+'/lookup/getallezopsclients',
			'datatype' : "array",
			'success' : function(data) {
				 for (var i=0, len=data.length; i < len; i++) {
		            $('#ezopsclient-class').append('<option value="' + data[i].clientId + '">' + data[i].clientName + '</option>');
		        }
			}
		});
        	
     		/*	var selectedAsset = null;
				$.ajax({
 					type : "GET",
 					'url' : ezopsContextPath+'/lookup/getallassets',
 					'datatype' : "array",
 					'success' : function(data) {
 						 for (var i=0, len=data.length; i < len; i++) {
 				            $('#asset-class').append('<option value="' + data[i].assetId + '">' + data[i].assetName + '</option>');
 				        }
 							var selectedAsset = $("#asset-class").val();
 					         if (selectedAsset) {
 					             var assetId = selectedAsset;
 					             console.log(assetId);
 					             $.ajax({
 						    		'async': false,
 						    		'global': false,
 						    		'url': ezopsContextPath+"/mapping/fieldmappings?assetclass="+assetId,
 						    		'datatype': "json",
 						    		'success': function(data){
 						    			 //ko.cleanNode(document.getElementById('fieldmapping'));
 						    			//ko.applyBindings(new GridModel(data));
 						    			var model = new GridModel(data);
 						                ko.applyBindings(model,document.getElementById('fieldmapping'));
 						                 mappinguimodel(model);
 						                 return;
 						    		}            
 								});
 					            
 					         }
 					}
 				});*/
				
					/*$("#asset-class").change(function () {
						console.log(this.value);
						var selectedAsset = this.value;
				         if (selectedAsset) {
				             var assetId = selectedAsset;
				             console.log(assetId);
				            
				            
				         }
				    });*/
	        	
            /*var assetSource = 
                {
                    dataType: "json",
                    url : ezopsContextPath+'/lookup/getallassets',
                    dataFields: [
                                 { name: 'assetName', type: 'string' },
                                 { name: 'assetId', type: 'string' }
                            ]
                 };
                
            $("#jqxDropDownList").on("bindingComplete", function () {
                var assetId = "0";
               // initGrid(assetId);
            });
               var assetDataAdapter = new $.jqx.dataAdapter(assetSource);
                
               $("#jqxDropDownList").jqxDropDownList(
               { 
                 selectedIndex: 0, 
                 source: assetDataAdapter, 
                 displayMember: "assetName", 
                 valueMember: "assetId"
               });
*/        	

     
   //Model that will be tied to the table
   
     // subscribe to the select event.
     /*$("#jqxDropDownList").on("bindingComplete", function () {
         var assetId = "0";
         var uimodel = new GridModel(initialData);
         mappinguimodel(uimodel);
     });
        var assetDataAdapter = new $.jqx.dataAdapter(assetSource);
         
        $("#jqxDropDownList").jqxDropDownList(
        { 
          selectedIndex: 2, 
          source: assetDataAdapter, 
          displayMember: "assetName", 
          valueMember: "assetId"
        });*/
     
         // prepare the data
         var source =
         {
             datatype: "json",
             datafields: [
                 { name: 'clientId' },
                 { name: 'clientName' }
             ],
             url: ezopsContextPath+'/lookup/getallezopsclients'
         };
         var dataAdapter = new $.jqx.dataAdapter(source);
         // Create a jqxDropDownList
         $("#clientJqxWidget").jqxDropDownList({
             selectedIndex: 0, source: dataAdapter, displayMember: "clientName", valueMember: "clientId", width: 200, height: 25
         });
         // subscribe to the select event.
         $("#clientJqxWidget").on('select', function (event) {
        	getAllClients();
         });
         
         function getAllClients(){
        	 $.ajax({
  	    		'url': ezopsContextPath+"/mapping/fieldmappings",
  	    		'datatype': "json",
  	    		'success': function(data){
  	    			var isBound = !!ko.dataFor(document.getElementById('fieldmappinggridparent'));
  	    			if(isBound){
  	    				ko.cleanNode(document.getElementById('fieldmappinggridparent'));
  	    			}
  	    			mappinguimodel(new GridModel(data));
  	    			 //var model = new GridModel(data);
		             //ko.applyBindings(model,document.getElementById('fieldmapping'));
		            // mappinguimodel(model);
  	    			 //ko.cleanNode(document.getElementById('fieldmapping'));
  	                 //mappinguimodel(new GridModel(data));
  	                 return;
  	    		}            
  			});
         }
        
/*    $("#ezopsclient-class").on('change', function (event) {
     	//console.log(event);
             
             $.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/mapping/fieldmappings",
	    		'datatype': "json",
	    		'success': function(data){
	    			 ko.cleanNode(document.getElementById('fieldmapping'));
	                 mappinguimodel(new GridModel(data));
	                 return;
	    		}            
			});
            
         
     });*/

     });
